<?php

class Sistema_UsuariosController extends App_Controller_Action
{
    private $_table     = 'USUARIOS';
    private $_pk        = 'USU_ID';
    private $_order_col = 'USU_NOME';
    private $_order     = 'ASC';
    private $_sta_col   = '';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'USU_FILE'; 
    public  $dir        = 'public/upload/';
    
    private $_PER_ID;
    private $_USU_ID;
    
    public $msg_log     = 'Login já cadastrado!';
    public $msg_eml     = 'E-mail já cadastrado!';
    
    public function init()
    {
        /* Initialize action controller here */
        $auth = Zend_Auth::getInstance();
        $s_user = $auth->getStorage();
        $this->_PER_ID = $s_user->read()->PER_ID;
        $this->_USU_ID = $s_user->read()->USU_ID;
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        
        
        $where = 'TUS_ID = 1'; //USU_TPO = 1';
        
        if($this->_USU_ID > 1){
            $where .= ' AND USU_ID <> 1'; 
        }
        if($this->_PER_ID > 2){ // <> de administrador
            $where .= ' AND USU_ID = '.$this->_USU_ID; // usuario logado
        }
        
        //$USU_STA = $this->_getParam('USU_STA', 1);
        //$where .= ' AND USU_STA = "'.$USU_STA.'"';
        
        $dscfiltro = $this->_getParam('dscfiltro', '');
        
        if($dscfiltro != '') $where .= ' AND USU_NOME LIKE "%'.$dscfiltro.'%"';
        
        $this->view->dscfiltro = $dscfiltro;
                
        
        
        $query = 'SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$where.' ORDER BY '.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
    }
    
    
    public function editAction() {
        $form = new Sistema_Form_Usuarios();
        //$form->submit->setLabel('Gravar');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_usuario.js?1=6'); 
        
        $this->view->form = $form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                $login = $this->validarlogin($formData['USU_ID'], $formData['USU_LOGIN']);
                if($login)  $msg = $this->msg_log;
                
                $email = $this->validaremail($formData['USU_ID'], $formData['USU_EMAIL']);
                if($email && $login == FALSE) $msg = $this->msg_eml;
        
                if($form->isValid($formData) && $login == FALSE && $email == FALSE) {
                    $id = (int) $form->getValue('USU_ID');
                    $data = array(
                        'USU_ID'        => $form->getValue('USU_ID'),
                        'USU_LOGIN'     => $form->getValue('USU_LOGIN'),	
                        //'USU_SENHA'     => sha1($form->getValue('USU_SENHA')),	
                        'USU_NOME'      => $form->getValue('USU_NOME'),
                        'USU_EMAIL'     => $form->getValue('USU_EMAIL'),
                        'PER_ID'        => $form->getValue('PER_ID'),
                        'USU_DATCAD'=> date('Y-m-d'),
                        //'USU_TPO'       => 1, // 1 = usuário
                        'TUS_ID'        => 1, 
                        'USU_CADSTA'    => 1,
                        'USU_STA'       => $form->getValue('USU_STA'),  
                    );

                    if(strlen($form->getValue('USU_SENHA')) > 1){
                        $data['USU_SENHA'] = sha1($form->getValue('USU_SENHA'));
                    }
                    
                    $this->db->beginTransaction();
                    if ($id == 0){
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();
                    }
                    else{                     
                        $this->db->update($this->_table,$data, $this->_pk.' = ' . $id);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                } else {
                    echo '<script>alert("'.$msg.'");</script>';
                    $form->populate($formData);
                }
            } catch(Exception $ex) {
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            
            if($this->_PER_ID <> 1 && $this->_PER_ID <> 2){ // <> de administrador
                if($this->_USU_ID <> $id){ // <> cod usuário logado
                    $this->_helper->redirector('index');
                }
            }
            
            if ($id > 0) {
                $obj = new Sistema_Model_DbTable_Usuarios();
                $form->populate($obj->fetchRow('USU_ID = ' . $id)->toArray());
            }
        }
    }

    public function deleteAction() {
        
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        
        $ok = FALSE;
        $msg = FALSE;
        
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ) {
            $this->db->beginTransaction();
            try{
                ///$data = array('USU_STA' => 0);
                //$ok = (bool) $this->db->update($this->_table,$data, 'USU_ID = ' . $id);
                $ok = (bool) $this->db->delete($this->_table, 'USU_ID = ' . $id);
                $this->db->commit();
            } catch(Exception $ex) {
                $msg = $ex->getMessage();
                $this->db->rollBack();
            }
        }
        
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
    public function validarlogin($id, $login) {
        
        $ok = FALSE;
         
        $where = '';
        if($id > 0){
            $query = 'SELECT SQL_CACHE USU_ID FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
            $row = $this->db->fetchRow($query);
            $where = '';
            if($row['USU_ID'] > 0) $where = 'USU_ID <> '.$row['USU_ID'].' AND ';
        }
        
        $where .= 'USU_LOGIN like "'.$login.'"';
        $query = 'SELECT SQL_CACHE USU_LOGIN FROM '.$this->_table.' WHERE '.$where;
        $result = $this->db->fetchAll($query);
        foreach($result as $res){
            if(strcasecmp($res['USU_LOGIN'], $login) == 0){
                $ok = TRUE;
            }
        }
        
        return $ok;
    }
    public function validarloginAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        
        $id = $this->_getParam('id', 0);
        $login = trim($this->_getParam('login', ''));
        
        $ok = $this->validarlogin($id, $login);
        if($ok)  $msg = $this->msg_log;

        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
    public function validaremail($id,$email) {
        
        $ok = FALSE;
        
        $where = '';
        if($id > 0){
            $query = 'SELECT SQL_CACHE USU_ID FROM '.$this->_table.' WHERE '.$this->_pk .' = ' . $id;
            $row = $this->db->fetchRow($query);
            $where = '';
            if($row['USU_ID'] > 0) $where = 'USU_ID <> '.$row['USU_ID'].' AND ';
        }
        
        $where .= 'USU_EMAIL like "'.$email.'"';
        $query = 'SELECT SQL_CACHE USU_EMAIL FROM '.$this->_table.' WHERE '.$where;
        $result = $this->db->fetchAll($query);
        foreach($result as $res){
            if(strcasecmp($res['USU_EMAIL'], $email) == 0){
                $ok = TRUE;
            }
        }
        
        return $ok;
    }
    public function validaremailAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        
        $id = $this->_getParam('id', 0);
        $email = trim($this->_getParam('email', ''));
        
        $ok = $this->validaremail($id, $email);
        if($ok)  $msg = $this->msg_eml;
        
        echo json_encode(array('ok' => $ok, 'msg' => $msg));
    }
    
}